package com.shop.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.ex.ShoppingException;
import com.shop.user.Interceptor.GetUserInfoInterceptor;
import com.shop.user.mapper.GoodsCommentMapper;
import com.shop.user.po.GoodsComment;
import com.shop.user.po.User;
import com.shop.user.service.GoodsCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author banxia
 * @since 2023-04-18
 */
@Service
public class GoodsCommentServiceImpl extends ServiceImpl<GoodsCommentMapper, GoodsComment> implements GoodsCommentService {

    @Autowired
    private GoodsCommentMapper goodsCommentMapper;

    @Override
    public void updateGoodsBaseComment(Long goodsId, Long rate) {
        goodsCommentMapper.updateGoodsBaseComment(goodsId, rate);
    }

    @Override
    @Transactional
    public void comment(Long rate, Long goodsId, String comment) {
        User user = GetUserInfoInterceptor.getUser();
        if (user == null) {
            ShoppingException.ThrowShoppingException("请先登录");
        }
        //保存评论
        GoodsComment goodsComment = new GoodsComment();
        goodsComment.setGoodsBaseId(goodsId);
        goodsComment.setRate(rate);
        goodsComment.setComment(comment);
        goodsComment.setUserId(user.getId());
        goodsComment.setUserName(user.getName());
        goodsComment.setCreateTime(new Date());
        goodsComment.setUpdateTime(new Date());
        save(goodsComment);
        //修改goods_base信息
        updateGoodsBaseComment(goodsId,rate);
    }

    //查看商品得分
    @Override
    public String getRate(Long goodsId) {
        return goodsCommentMapper.getrate(goodsId);
    }

    @Override
    public List<GoodsComment> getComment(Long goodsId) {
        LambdaQueryWrapper<GoodsComment> wrapper=new LambdaQueryWrapper();
        wrapper.eq(GoodsComment::getGoodsBaseId,goodsId);
        List<GoodsComment> goodsComments = goodsCommentMapper.selectList(wrapper);
        return goodsComments;
    }
}
